<?php
//在线预订
define('IN_T',true);
require 'include/init.php';
require_once '../source/include/cls_weixin.php';

$c_id = intval($_REQUEST['cid']);

//读取商户基本信息
$sql = "SELECT c.* FROM ".$Base->table('company_profile')." as c WHERE c.c_id = $c_id";

$company_profile = $Db->query($sql,"Row");

//商户不存在或未完善资料
if(empty($company_profile)){
	echo '商家不存在或未完善基本信息！';
	exit;
}

//商家未开通在线预订
if(!$company_profile['is_book']){
	echo '商家未开通在线预订！';
	exit;
}

$tp->assign('company_profile',$company_profile);

//微信未登录，微信登录
if(($_SESSION['customer']['id']<1)){
	//查询订单商家是否配置微信支付
	$payment = $Db->query("select * from ".$Base->table('company_payment')." where c_id=$c_id limit 1",'Row');
	if(!empty($payment)){
		unset($payment['id']);
		unset($payment['c_id']);
		$_lang['wxpay_config'] = $payment;
	}
	//实例化微信登录
	$wx = new Weixin($_lang['wx_config']['appid'],$_lang['wx_config']['appsecret']);
	$param = array(
		'scope'=>'snsapi_userinfo',
		'redirect_uri'=>$_lang['host'].'book/?cid='.$c_id,
	);
	$user = $wx->loginWeixin($param);
	if($user){
		//$head_img = GrabImage($customer['headimgurl']);
		//setcookie('wx[openid]',$customer['openid'],time()+1296000,"/");
		//setcookie('wx[head_img]',$head_img,time()+1296000,"/");
		//setcookie('wx[nickname]',$customer['nickname'],time()+1296000,"/");
		//setcookie('wx[sex]',$customer['sex'],time()+1296000,"/");
		//setcookie('wx[province]',$customer['province'],time()+1296000,"/");
		//setcookie('wx[city]',$customer['city'],time()+1296000,"/");
		//是否已注册
		$customer = $Db->query("select * from ".$Base->table('company_customer')." where openid='".$user['openid']."' limit 1",'Row');
		//未注册，执行注册
		if(!$customer){
			$data = array(
			'openid'=>$user['openid'],
			'nickname'=>$user['nickname'],
			'head_img'=>$user['headimgurl'],
			'sex'=>$user['sex']==0?'未知':($user['sex']==1?'男':'女'),
			'province'=>$user['province'],
			'city'=>$user['city'],
			);
			$uid = $Db->insert($Base->table('company_customer'),$data);
			$data['id'] = $uid;
			$_SESSION['customer'] = $data;
		}
		else{
			$_SESSION['customer'] = $customer;
		}
	}
}

$act = Common::sfilter($_REQUEST['act']);

//填写人数
if($act=='people_num'){
	$res['status'] = 0;
	$people_num = intval($_POST['people_num']);
	if($people_num<1 && $people_num>100){
		$res['msg'] = '人数须介于1-100之间';
	}
	else{
		$res['status'] = 1;
	}
	echo $Json->encode($res);
	exit;
}
//填写手机号
else if($act == 'phone'){
	$res['status'] = 0;
	$phone = Common::sfilter($_POST['phone']);
	if(!Common::is_mobile($phone)){
		$res['msg'] = '请填写正确的手机号';
	}
	else{
		$res['status'] = 1;
	}
	echo $Json->encode($res);
	exit;
}
//订单些信息写入数据库
else if($act == "write_order"){
	$re['status'] = 0;
    $list = $_POST['products'];//点单的商品信息
    $data['phone']= Common::sfilter($_POST['phone']);
    $data['people_num'] = intval($_POST['people_num']);
    $data['table_num'] = intval($_POST['table_num']);
    $data['price'] = number_format($_POST['cart_price'],2,'.','');
    $data['c_id'] = $c_id;
    $data['order_status'] = 0;
    $data['creattime'] = date('Y-m-d H:i:s',Common::gmtime());
    $data['u_id'] = $_SESSION['customer']['id'];//微信登录后获取
    $data['type'] = intval($_POST['type']);
    $data['fp'] = Common::sfilter($_POST['fp']);
	
	if(!Common::is_mobile($data['phone'])){
		$re['msg'] = '手机号不正确';
	}
	else if($data['people_num']<1){
		$re['msg'] = '请至少填写一个到店人数';
	}
	else if(empty($list)){
		$re['msg'] = '请至少选择一个商品预订';
	}
	else if($data['price']<0){
		$re['msg'] = '订单金额不能为负';
	}
	else{
		//通过客户传递的商品数量，和数据库查询的商品价格对比price是否一致
		$total_price = 0;
		//订单商品
		$order_products = array();
		foreach($list as $k => $v) {
			foreach($v['goods'] as $ke => $va){
				$order_products[] = array(
					'pid'=>intval($va['id']),
					'name'=>Common::sfilter($va['title']),
					'price'=>number_format($va['price'],2,'.',''),
					'num'=>intval($va['num']),
					'remark'=>Common::sfilter($va['remark']),
				);
				$price = $Db->query('SELECT price FROM '.$Base->table('company_product').' WHERE id='.$va['id'],"One");
				$total_price += $price*$va['num'];
			}
		}
		
		//echo $total_price.'-'.$data['price'];exit;
	    if ($total_price != $data['price']) {
			
	        $re['msg'] = '订单金额验证失败！';
	    }
	    else{    
		   //生成订单号
		   $error_no = 0;
		   do{
				$order_num = Common::get_order_sn(); //生成订单号
				$error_no = $Db->query("select id from ".$Base->table('company_order')." where order_num = '".$order_num."'",'One');
		   }
		   while($error_no); //如果是订单号重复则重新生成
		   
		   $data['order_num'] = $order_num;
	       $Db->beginTransaction();
		   //将订单添加到订单表中
            if($data['price'] == 0){
                //当订单金额为0时，直接修改订单为已支付
                $data["order_status"] = 2;
            }
		   $id = $Db->insert($Base->table('company_order'),$data);
		   //将订单详情写入到详情表
		   if($id){
			  foreach($order_products as $k=>$v){
				  $v['oid'] = $id;
				  $Db->insert($Base->table('company_order_products'),$v);
			  }	
			  $re = array('status'=>1,'oid'=>$id);
		   }
		   $Db->commit();
	    }
   }
   echo $Json->encode($re);
   exit;
}
//订单的详情
else if($act=="order_info"){
	$re['status'] = 0;
	$oid = intval($_POST['oid']);

	$order = $Db->query("SELECT * FROM ".$Base->table('company_order')." WHERE id = $oid",'Row');

	if(empty($order)){
		$re['msg'] = '该订单不存在';
	}
	else{
		$sql = "SELECT i.* FROM ".$Base->table('company_order_products')." as i WHERE i.oid = $oid ORDER BY i.id";
		//print_r($sql);
		$info = $Db->query($sql);
		$re['info'] = $info;
		$order['order_status_title'] = $_lang['order_status_title'][$order['order_status']];
		$order['order_status_lang'] = $_lang['order_status'][$order['order_status']];
		$order['order_status_brief'] = $_lang['order_status_brief'][$order['order_status']];
		$re['order'] = $order;
		$re['status'] = 1;
	}
	//print_r($re);
	echo $Json->encode($re);
	exit;
}
//订单列表
else if($act=="order_list"){
	$re['status'] = 1;
	$page = intval($_POST['page']);
	$page = $page<1 ? 1: $page;
	$pageSize = 10;
	$u_id = $_SESSION['customer']['id'];//用户登录写入SEEEION
	$sql = "SELECT * FROM ".$Base->table('company_order')." WHERE u_id=$u_id AND c_id=$c_id ";
	$listCount = count($Db->query($sql));
	$sql .= "ORDER BY id DESC limit ".($page-1)*$pageSize.", $pageSize";
	$list = $Db->query($sql);
	foreach($list as $k=>$v){
		$list[$k]['order_status_lang'] = $_lang['order_status'][$v['order_status']];
	}
	$re['list'] = $list;
	if(ceil($listCount/$pageSize) > $page){
		$re['next'] = $page+1;
	}
	echo $Json->encode($re);
	exit;
}
else{
	//商家所有开通预订的分类
	$sql = "SELECT id,name,unit,pid FROM ".$Base->table('company_product_cat')." WHERE cid=$c_id and is_book=1 order by sort asc, id asc";
	$cat = $Db->query($sql);
	$cat_sub = array();
	//分类下所有商品
	foreach($cat as $k=>$v){
		$sql = "SELECT * FROM ".$Base->table('company_product')." WHERE c_id=$c_id ".
		       "and cat_id=".$v['id']." ".
			   "order by sort asc,id asc";
		$products = $Db->query($sql);
		foreach($products as $k2=>$v2){
			$products[$k2]['unit'] = empty($v['unit'])? '' : '/'.$v['unit'] ;
		}
		//子分类，单独整合
		if($v['pid']>0){
			$cat_sub_tmp = $v;
			$cat_sub_tmp['products'] = $products;
			$cat_sub[$v['pid']][] = $cat_sub_tmp;
			unset($cat[$k]);
		}
		else{
			$cat[$k]['products'] = $products;
		}
	}
	
	//print_r($cat);print_r($cat_sub);
	
	//多个父分类，整合子分类的products到父分类
	if(count($cat)>1){
		foreach($cat as $k=>$v){
			if(!empty($cat_sub[$v['id']])){
				foreach($cat_sub[$v['id']] as $v2){
					$cat[$k]['products'] = array_merge($cat[$k]['products'],$v2['products']);
				}
			}
		}
	}
	//1个父分类
	else{
		//且有子分类，则切换
		if(!empty($cat_sub)){
			$cat = array_shift($cat_sub);
		}
	}
	
	//print_r($cat);print_r($cat_sub);
	
	$tp->assign('cat',$cat);
}

$tp->assign('act',$act);
$tp->display('book.tpl');

?>